<template>
	<view class="page">
		<!-- 返回样式 -->
		<view class="returnbox" @click="fanhuidata">
			<image src="../../static/fanhui.png"></image>
		</view>
		<!-- 视频区域 -->
		<view class="videoarea">
			<view id="videoContain" style="width: 100%;height: 100%" preload="auto" playsinline webkit-playsinline>
			    <!-- <video id="player-container-id"  preload="auto" playsinline webkit-playsinline></video> -->
			</view>
			
			<view class="operation">
				<view v-if="operationvalue" class="operationlist">
					<image src="../../static/icon/aa/playingmethod.png"></image>
					<view style="font-size: 25rpx;">规则</view>
				</view>
				<view v-if="operationvalue" class="operationlist">
					<image src="../../static/icon/aa/appeal.png"></image>
					<view style="font-size: 25rpx;">申诉</view>
				</view>
				<view v-if="operationvalue" @click="voiceat" class="operationlist">
					<image v-if="voiceavalue" src="../../static/icon/aa/openmusic.png"></image>
					<image v-else src="../../static/icon/aa/closemusic.png"></image>
					<view style="font-size: 25rpx;">静音</view>
				</view>
				<view @click="operat" class="openmethod">
					<image
						:src="operationvalue==false?'../../static/icon/aa/openoperation.png':'../../static/icon/aa/closeoperation.png'">
					</image>
				</view>
			</view>
		</view>


		<!-- 商品操作区域 -->
		<view class="grabbox">

			<!-- 开始游戏区域 -->
			<view v-if="startth==false">
				<view class="grablist">
					<view class="grab_commodity">
						<image class="grab_commodity_image"
							src="https://duimianimg.loovee.com/MediaServerMblove/servlet/Proxy/PhotoServlet/63313ec0f0607e1ca0e46f595593f455.jpg?w=800&h=800">
						</image>
						<view class="grab_commodity_text">订单详情</view>
					</view>
					<view v-if="state == 'ready'"  @click="startthegame" class="startbox">
						<view class="startext">20金币/次</view>
					</view>
					
					<view v-if="state == 'await'"   class="startboxyyu">
						<!-- <view class="startext">20金币/次</view> -->
					</view>
					
					
					<view class="currency">
						<image class="currency_image" src="../../static/icon/aa/coins.png"></image>
						<view class="currency_num">23</view>
					</view>
				</view>
				<view class="grabtextlist flex ac">
					<view style="font-size: 27rpx;">可兑 0 积分</view>
					<view style="font-size: 27rpx;">畅玩卡: 1张</view>
					<view class="flex ac">
						<view class="zhao">甩爪</view>
						<view style="font-size: 27rpx;">NO:P1036</view>
					</view>
				</view>
				<view v-if="stateShow" class="calculate">{{countdownTime}}</view>
			</view>
			<!-- 遥控游戏区域 -->
			<view v-if="startth==true">
				<view class="controlbox">
					<view class="controw">
						<view @touchstart="handleTouchStart('left')"
				              @touchend="handleTouchEnd('stop')">
							<image src="../../static/icon/aa/left.png"></image>
						</view>
						<view style="width: 140rpx;height:100rpx;"></view>
						<view @touchstart="handleTouchStart('right')"
				              @touchend="handleTouchEnd('stop')">
							<image src="../../static/icon/aa/right.png"></image>
						</view>
					</view>
					<view class="contcolumn" >
						<view @touchstart="handleTouchStart('top')" 
				              @touchend="handleTouchEnd('stop')">
							<image src="../../static/icon/aa/top.png"></image>
						</view>
						<view style="width: 100rpx;height:80rpx;"></view>
						<view @touchstart="handleTouchStart('down')"
				              @touchend="handleTouchEnd('stop')">
							<image src="../../static/icon/aa/bottom.png"></image>
						</view>
					</view>
					<view @click="controgo" class="controgo">
						<image src="../../static/icon/aa/go.png"></image>
					</view>
					
				</view>
				<view class="controllist flex ac">
					<view class="flex ac">
						<view class="zhao">甩爪</view>
						<view style="font-size: 27rpx;color: #86878D;">NO:P1036</view>
					</view>
					<view class="contronum">
						<image class="contronumleft" src="../../static/icon/aa/jingbi.png"></image>
						<view style="font-size: 27rpx;">10币</view>
						<image class="contronumright" src="../../static/icon/aa/jia.png"></image>
					</view>
				</view>
				
				
				
			</view>
		</view>
	</view>
</template>

<script>
	import {
		request
	} from "@/static/common.js";
	export default {
		data() {
			return {
				startth: false,
				voiceavalue: true,
				operationvalue: false,
				commodity_id:'',
				token:'',
				name:'',
				state:'',
				stateShow:false,
				countdowntimerdata:null,//心跳
				countdownTime: 3, //倒计时
			}
		},
		onLoad(option) {
			console.log('参数1:', option); // 输出 value1
			this.commodity_id = option.id
			this.getmachine()
			
		},
		mounted() {
		    this.tcpalyer();
		},
		methods: {
			async getmachine(e) {
				let apply = await request(`${getApp().globalData.http}commodity/get_machine`, {
					'X-Requested-With': 'XMLHttpRequest',
					'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
				}, "GET", {
					commodity_id: this.commodity_id,
				})
				if (apply.data.code == 0) {
					  console.log('哇哇》》',apply.data.data)
					  this.count = apply.data.data[0].count
					  this.name = apply.data.data[0].name
					  this.connectSocket()
				} else {
					uni.showToast({
						title: `${apply.data.message}`,
						icon: "none",
					})
				}
			},
			handleTouchEnd(text) {
			      // 松开事件处理
			      console.log('松开事件处理', text);
				  let data = {
				  	'direction':text
				  }
				  
				  this.sendSocketMessage(JSON.stringify(data))
				  
			    },
			handleTouchStart(text){
				console.log('按下事件处理', text);
				let data = {
					'direction':text
				}
				 
				this.sendSocketMessage(JSON.stringify(data))
				
			},
			// 抓娃娃
			controgo(e){
				var data = {
						'direction':"catch",
						}
				this.sendSocketMessage(JSON.stringify(data))		
			},
			//开始游戏
			startthegame(e) {
				var that = this
				let data = {}
				let datas = {}
				// 链接娃娃机
				data = {
						'direction':"connect",
						}
					
			     // this.startth = true
							 
			   that.sendSocketMessage(JSON.stringify(data))	
			   this.stateShow = true
			   this.turnCountdown()
			 //    // 游戏开始
				// setTimeout(() => {
				// 		        // 这里写你需要延时一秒后执行的代码
				// let datas = {
				// 		'direction':"start",
				// 	}
				// 	console.log(datas)
					
				// 	// that.sendMessage(JSON.stringify(datas))
				// }, 1000);
				// // 游戏开始2
				// setTimeout(() => {
				// 		        // 这里写你需要延时一秒后执行的代码
				// let datass = {
				// 		'direction':"start",
				// 	}
				// 	console.log(datass)
				// 	// that.sendMessage(JSON.stringify(datass))
				// }, 2000);
			 //   console.log(data) 
			   
			    // that.sendMessage(JSON.stringify(data))
				
			},
			
			
			//连接websocket
			connectSocket() {
							let that = this;
							console.log('调用连接websocket')
							var token = getApp().globalData.token
							this.socketTask = uni.connectSocket({
								
								    // url: 'ws://120.55.52.136:9090/ws/connect/TestConsumer',
									// url: 'ws://120.55.52.136:9090/ws/connect/user/'+that.uid+'/',
									// url: 'ws://120.55.52.136:9090/ws/user/XlclZ1ZVUU4xX3VzZXI=/4/t001/',
									url: 'ws://120.55.52.136:9090/ws/user/'+token+'/'+this.commodity_id+'/'+this.name+'/',
									// url:'ws://120.55.52.136:9090/ws/user/Nm55TEZxXzE3MTg1MTk0MzhfMQ/71/t001/',
								
									header: {  
									            Authorization:2,  
									        },
									success(res) {
										
										that.heart()
										console.log("websocket连接成功");
										// that.isSuccess = true
									},
									fail(err) {
										console.log("报错", err);
									}
								},
			 
			 
							);
						
							that.socketTask.onMessage(function(res) {
								var data = JSON.parse(res.data)
								
								// console.log('2收到服务器内容：' ,typeof data);
								// console.log('3收到服务器内容' ,data);
								if(data.code == '0'){
									
									that.state = data.message
									console.log('返回数据》》》',that.state)
									if(data.message == '连接成功'){
										let datas = {
												'direction':"start",
											}
											console.log(datas)
											that.sendSocketMessage(JSON.stringify(datas))
										// setTimeout(() => {
										// 		        // 这里写你需要延时一秒后执行的代码
										// let datas = {
										// 		'direction':"start",
										// 	}
										// 	console.log(datas)
											
										// 	// that.sendMessage(JSON.stringify(datas))
										// }, 1000);
										// 游戏开始2
										setTimeout(() => {
												        // 这里写你需要延时一秒后执行的代码
										let datass = {
												'direction':"start",
											}
											console.log(datass)
											that.sendSocketMessage(JSON.stringify(datass))
										}, 2000);
										
									}else if(data.message =='start'){
										// 已经开启游戏中
										that.startth = true
									}else if(data.message =='游戏开始'){
										// 已经开启游戏中
										that.startth = true
									}else if(data.message =='你已开始游戏，请勿重复开始'){
										// 已经开启游戏中
										that.startth = true
									}else if(data.message =='游戏结束清重新开始'){
										// 游戏结束清重新开始
										
										that.state = 'ready'
										that.startth = false
									}else if(data.message =='恭喜成功抓中'){
										// 游戏结束清重新开始
										that.state = 'ready'
										that.startth = false
										
									}
									
									
									// if(data.message == 'ready'){
									// 	// that.socketTask.close()
									// 	// 防止重复获取
									// 	if (that.codeTime > 0) {
									// 		return
									// 	}
									// 	// 倒计时
									// 	that.codeTime = 10
									// 	// 箭头函数可以直接拿到外面的this的内容
									// 	that.timer = setInterval(() => {
									// 		if (that.codeTime >= 1) {
									// 			that.codeTime--
									// 			that.codeTime = that.codeTime
									// 			console.log('倒计时1',that.codeTime)
									// 		} else {
									// 			that.socketTask.close()
									// 			console.log('倒计时2')
									// 			clearInterval(that.timer)
									// 		}
									// 	}, 1000)
									// }else if(data.message == '游戏结束清重新开始'){
									// 	that.socketTask.close()
									// }
									
									
								}
								// that.handlerMsg(JSON.parse(res.data)) //这里是对获取到的数据进行操作
							});
			 
			 
						},
			
			//发送消息
				sendSocketMessage(msg) {
							console.log('发送信息')
							
							console.log(msg)
							let that = this;
							return new Promise((reslove, reject) => {
								that.socketTask.send({
									data: msg,
									success(res) {
										console.log('发送成功')
										reslove(res)
									},
									fail(res) {
										console.log('发送失败')
										console.log(res)
										// reject(res)
									}
								});
							})
			 
						},
			//打开或者关闭操作
			operat(e) {
				this.operationvalue = !this.operationvalue
			},

			//打开或者关闭声音
			voiceat(e) {
				this.voiceavalue = !this.voiceavalue
			},

			

			//返回
			fanhuidata(e) {
				uni.navigateBack()
				uni.closeSocket({
						success() {
							console.log("手动关闭成功！");
							// clearInterval(Time) //关闭定时器
							// clearInterval(XTime) //关闭心跳定时器
							// // 确保已经关闭
							// socketTask = null;
						}
					})
				  // clearInterval(this.timer)
				  clearInterval(this.xintimer)
				  this.codeTime = 0;
				  this.timer = null
				  this.xintimer = null
			},
			//返回上个页面关闭ws
			destroyCountdown() {
				uni.closeSocket({
						success() {
							console.log("手动关闭成功！");
							// clearInterval(Time) //关闭定时器
							// clearInterval(XTime) //关闭心跳定时器
							// // 确保已经关闭
							// socketTask = null;
						}
					})
			      // clearInterval(this.timer)
				  clearInterval(this.xintimer)
			      this.codeTime = 0;
				  this.timer = null
				  this.xintimer = null
			    },
			// 开启倒计时
			turnCountdown() {
				// countdowntimerdata:null,//心跳
				// countdownTime: 0, //倒计时
				let that = this;
				clearInterval(that.countdowntimerdata);
				that.countdowntimerdata = '';
				that.countdownTime = 3
				let msg = {
					"direction": "active",
				}
				that.countdowntimerdata = setInterval(() => {
					that.countdownTime--
					console.log(that.countdownTime)
							if (that.countdownTime >= 1) {
								that.countdownTime
								that.countdownTime = that.countdownTime
								console.log('倒计时1',that.countdownTime)
							} else {
								that.stateShow =false
								console.log('倒计时2')
								clearInterval(that.countdowntimerdata)
							}
					// if(that.countdownTime =3){
					// 	clearInterval(that.countdowntimerdata);
					// }
				}, 1000)
			},	
			tcpalyer() {
			    // sdk引入有顺序
			    // let script1 = document.createElement("script");
			    // script1.type = "text/javascript";
			    // script1.src =
			    // "https://web.sdk.qcloud.com/player/tcplayer/release/v5.1.0/tcplayer.v5.1.0.min.js";
			    // document.getElementsByTagName("head")[0].appendChild(script1);
			    // 创建script标签，引入外部文件
			    let script = document.createElement("script");
			    script.type = "text/javascript";
			    script.src =
			    "https://web.sdk.qcloud.com/player/tcplayer/release/v5.1.0/tcplayer.v5.1.0.min.js";
			    document.getElementsByTagName("head")[0].appendChild(script);
			    
			    const video = document.createElement("video")    
			    video.setAttribute("id", "player-container-id")
			    video.setAttribute('playsinline',true)
				
			    video.setAttribute('webkit-playsinline',true)
				video.setAttribute('muted',true)
			    video.setAttribute('autoplay',true)
				
				video.setAttribute('webkit-playsinline',true)// video的属性
				
			    document.getElementById("videoContain").appendChild(video)
			    
				
				
				
				
			    // 引入成功
			    script.onload = function () {
			        console.log("js资源加载成功了");
			        var player = TCPlayer('player-container-id', {
			            sources: [{
			              src: 'webrtc://www.gdzhuizi.com/live/85bf64d66a465343c5fb9562aa6946dbLive0', // 播放地址
			            }],
			            licenseUrl: 'https://license.vod2.myqcloud.com/license/v2/1258173912_1/v_cube.license', // license 地址，参考准备工作部分，在视立方控制台申请 license 后可获得 licenseUrl
			        });
					
					// 微信
					document.addEventListener(
					    'WeixinJSBridgeReady',
					    function () {
					      const video = document.querySelector('video');
					      video && video.play();
					    },
					    false,
					  );
					  
					  video.addEventListener('loadeddata', function() {
					      // 当视频加载完成后，自动播放
					      video.play();
					    });
			    };
				
				
				
			    // 引入失败
			    script.onerror = function () {
			        console.log("js资源加载失败了");
			    };
			},
			//心跳
						heart() {
							let that = this;
							clearInterval(this.xintimer);
							this.xintimer = '';
							let msg = {
								"direction": "active",
							}
							this.xintimer = setInterval(() => {
								 that.sendSocketMessage(JSON.stringify(msg)).then(res => {
									console.log('心跳成功')
								}).catch(res => {
									console.log('发送失败')
								console.log((res))
								 })
			 
							}, 10000)
						},	
		}
	}
</script>

<style lang="scss" scoped>
	@import url('https://imgcache.qq.com/open/qcloud/video/tcplayer/tcplayer.css');
	page {
		width: 100%;
		height: 100%;
		background-color: #f7f8fa;
		display: flex;
		flex-flow: column;
		overflow: hidden;
	}
	
	*{
	            -webkit-touch-callout:none; /*系统默认菜单被禁用*/ 
	            -webkit-user-select:none; /*webkit浏览器*/ 
	            -khtml-user-select:none; /*早期浏览器*/ 
	            -moz-user-select:none;/*火狐*/ 
	            -ms-user-select:none; /*IE10*/ 
	            user-select:none; 
	        } 
	        input { 
	            -webkit-user-select:auto; /*webkit浏览器*/ 
	        }
	        textarea {          
	            -webkit-user-select:auto; /*webkit浏览器*/ 
	        }
	img{
		pointer-events: none;
	}
	input,textarea {
	  -webkit-user-select:auto; /*webkit浏览器*/
	  margin: 0px;
	  padding: 0px;
	  outline: none;
	}

	.page {
		width: 100%;
		height: 100%;
		display: flex;
		flex-flow: column;
		overflow: hidden;
	}

	//返回样式
	.returnbox {
		width: 88rpx;
		height: 88rpx;
		position: fixed;
		top: 25rpx;
		left: 20rpx;
		z-index: 999;
	}

	.returnbox image {
		width: 100%;
		height: 100%;
	}

	// 视频区域
	.videoarea {
		// width: 100%;
		// height: 83vh;
		// flex: 1;
		overflow: scroll;
		width: 100%;
		background-color: red;
		position: relative;
	}

	.operation {
		width: 85rpx;
		background: rgba(0, 0, 0, 0.45);
		position: absolute;
		bottom: 100rpx;
		right: 20rpx;
		border-radius: 25rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		padding: 18rpx 0;

	}

	.openmethod {
		width: 85rpx;
		display: flex;
		justify-content: center;
	}

	.openmethod image {
		width: 56rpx;
		height: 56rpx;
	}

	.operationlist {
		width: 85rpx;
		display: flex;
		justify-content: center;
		flex-direction: column;
		align-items: center;
		color: #ffffff;
		margin-bottom: 15rpx;
	}

	.operationlist image {
		width: 67rpx;
		height: 67rpx;
	}

	//商品操作区域
	.grabbox {
		width: 100%;
		height: 230rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		background-color: #ffffff;
	}

	//开始游戏区域
	.grablist {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 35rpx;
	}

	.grab_commodity {
		width: 120rpx;
		height: 120rpx;
		border-radius: 20rpx;
		position: relative;
	}

	.grab_commodity_image {
		width: 100%;
		height: 100%;
		border-radius: 20rpx;
	}

	.grab_commodity_text {
		width: 100%;
		height: 39rpx;
		background-color: rgba(0, 0, 0, 0.5);
		position: absolute;
		left: 0;
		bottom: 0;
		font-size: 23rpx;
		color: #ffffff;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 0 0 20rpx 20rpx;
	}

	.startbox {
		width: 350rpx;
		height: 120rpx;
		background-size: 100% 100%;
		background-repeat: no-repeat;
		background-image: url('../../static/icon/aa/startthegame.png');
	}
	
	.startboxyyu {
		width: 350rpx;
		height: 120rpx;
		background-size: 100% 100%;
		background-repeat: no-repeat;
		background-image: url('../../static/icon/aa/yys.png');
	}

	.startext {
		font-size: 27rpx;
		color: #ffffff;
		text-align: center;
		margin-top: 70rpx;
	}

	.currency {
		width: 120rpx;
		height: 120rpx;
		background-color: rgba(1, 1, 1, 0.3);
		// background-color: #4CE52E;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		border-radius: 20rpx;
	}

	.currency_image {
		width: 80rpx;
		height: 80rpx;
	}

	.currency_num {
		font-size: 26rpx;
		color: #ffffff;
		margin-top: -9rpx;
	}

	.grabtextlist {
		padding: 20rpx 20rpx 0 20rpx;
		justify-content: space-between;
		color: #86878D;
	}

	.zhao {
		background-image: linear-gradient(270deg, #FF6144 0%, #FF99C9 100%);
		color: #ffffff;
		font-size: 23rpx;
		padding: 2rpx 5rpx;
		border-radius: 5rpx;
		margin-right: 5rpx;
	}


	// 遥控游戏区域
	.controlbox {
		width: 100%;
		height: 200rpx;
		position: relative;
		margin-top: -170rpx;
	}

	.controw {
		position: absolute;
		left: 50rpx;
		top: 50rpx;
		display: flex;
		align-items: center;
		z-index: 99;
	}

	.controw image {
		width: 150rpx;
		height: 150rpx;
	}

	.contcolumn {
		position: absolute;
		left: 190rpx;
		top: -40rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		z-index: 99;
	}

	.contcolumn image {
		width: 150rpx;
		height: 150rpx;
	}

	.controgo {
		position: absolute;
		right: 50rpx;
		top: 35rpx;
		width: 180rpx;
		height: 180rpx;
		z-index: 99;
	}

	.controgo image {
		width: 100%;
		height: 100%;
	}

	.controllist {
		width: 100%;
		display: flex;
		justify-content: space-between;
		position: absolute;
		left: 0;
		bottom: 20rpx;
		padding: 0 20rpx;
	}

	.contronum {
		height: 50rpx;
		background-color: red;
		border-radius: 50rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		// position: absolute;
	}

	.contronumleft {
		width: 50rpx;
		height: 50rpx;
		margin-right: 10rpx;
	}

	.contronumright {
		width: 35rpx;
		height: 35rpx;
		margin-left: 10rpx;
		margin-right: 10rpx;
	}
	
	// 倒计时
	.calculate{
		width: 100rpx;
		height: 100rpx;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 199;
		position: absolute;
		top: 30%;
		left: 42%;
		border-radius: 50%;
		text-align: center;
        line-height:100rpx;
		font-size: 50rpx;
		color: #ffffff;
	}
</style>